package com.ly.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/upload")
public class FileUpload1Controller {

    // OSS 配置信息
    private static final String ENDPOINT = "https://oss-cn-shenzhen.aliyuncs.com";
    private static final String BUCKET_NAME = "lyproject-big-event";

    // 通过环境变量获取凭证
    private final EnvironmentVariableCredentialsProvider credentialsProvider =
            CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

    public FileUpload1Controller() throws com.aliyuncs.exceptions.ClientException {
    }

    @PostMapping("/file")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        // 初始化 OSSClient
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, credentialsProvider);

        try (InputStream inputStream = file.getInputStream()) {
            // 使用上传的文件名作为对象名
            String objectName = file.getOriginalFilename();

            // 上传文件到 OSS
            ossClient.putObject(BUCKET_NAME, objectName, inputStream);
            return "File uploaded successfully: " + objectName;
        } catch (OSSException | ClientException e) {
            return "OSS Exception: " + e.getMessage();
        } catch (IOException e) {
            return "IO Exception: " + e.getMessage();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
